import { getByPCode } from '@/apis/getByPCode'
import { Cascader } from 'antd'
import { useState } from 'react'
interface ProvinceProps {
    onChange?: (value: any) => void
    disabled?: boolean//禁用
    placeholder?: string
    value: any
}
interface ProvinceItem extends AreaVO {
    children?: AreaVO[]
    isLeaf?: boolean
}
function ProvinceCity(props: ProvinceProps) {
    const [provinceList, setprovinceList] = useState<ProvinceItem[]>([])
    //第一次获取省
    async function onProvfocusBtn() {
        let res = await getByPCode({ code: '0' })
        setprovinceList(res.data.map((item: ProvinceItem) => { item.isLeaf = false; return item }))
    }
    //调用获取市
    async function loadData(selectedOptions: ProvinceItem[]) {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        let res = await getByPCode({ code: targetOption.code || '' })
        targetOption.children = res.data
        setprovinceList([...provinceList])
    }
    function onChange(_value: any, selectedOptions: ProvinceItem[]) {
        if (props.onChange) {
            let list = selectedOptions.map((item: ProvinceItem) => ({ code: item.code, name: item.name }))
            props.onChange(list)
        }
    }
    let value = props.value && props.value.map((item: any) => item.name)
    return (
        <Cascader
            onFocus={onProvfocusBtn}
            options={provinceList}
            value={value}
            loadData={loadData}
            onChange={onChange}
            disabled={props.disabled}
            placeholder={props.placeholder}
            fieldNames={{ label: 'name', value: 'code' }}
        />

    )
}

export default ProvinceCity